package com.ruoyi.system.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.security.Md5Utils;
import com.ruoyi.system.domain.SysFactory;
import com.ruoyi.system.domain.SysPost;
import com.ruoyi.system.domain.SysRole;
import com.ruoyi.system.domain.SysSupplier;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.domain.SysUserFactory;
import com.ruoyi.system.domain.SysUserPost;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.domain.SysUserSupplier;
import com.ruoyi.system.mapper.SysFactoryMapper;
import com.ruoyi.system.mapper.SysPostMapper;
import com.ruoyi.system.mapper.SysRoleMapper;
import com.ruoyi.system.mapper.SysSupplierMapper;
import com.ruoyi.system.mapper.SysUserFactoryMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.SysUserPostMapper;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.system.mapper.SysUserSupplierMapper;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;

import cn.hutool.core.util.ArrayUtil;

/**
 * 用户 业务层处理
 *
 * @author ruoyi
 */
@Service
public class SysUserServiceImpl implements ISysUserService
{
    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);

    @Autowired
    private SysUserMapper       userMapper;

    @Autowired
    private SysRoleMapper       roleMapper;

    @Autowired
    private SysFactoryMapper       factoryMapper;

    @Autowired
    private SysSupplierMapper       supplierMapper;

    @Autowired
    private SysPostMapper       postMapper;

    @Autowired
    private SysUserSupplierMapper       userSupplierMapper;

    @Autowired
    private SysUserFactoryMapper       userFactoryMapper;

    @Autowired
    private SysUserPostMapper   userPostMapper;

    @Autowired
    private SysUserRoleMapper   userRoleMapper;

    @Autowired
    private ISysConfigService   configService;

    /**
     * 根据条件分页查询用户列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectUserList(SysUser user)
    {
        return userMapper.selectUserList(user);
    }

    /**
     * 根据条件分页查询已分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectAllocatedList(SysUser user)
    {
        return userMapper.selectAllocatedList(user);
    }

    /**
     * 根据条件分页查询未分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectUnallocatedList(SysUser user)
    {
        return userMapper.selectUnallocatedList(user);
    }

    /**
     * 模糊查询用户名和用户部门
     *
     * @param userName 用户名
     * @return 用户和用户部门
     */
    public List<SysUser>  selectUserNameByName(SysUser sysUser)
    {
    	//sql中使用${}，需检查参数是否含字母，防止sql注入
    	List <SysUser> internalUser = new ArrayList<SysUser>();
    	if (StringUtils.isNotEmpty(sysUser.getDeptIds()) && sysUser.getDeptIds() != null && judgeContainsStr(sysUser.getDeptIds()))
    	{
    		sysUser.setDeptIds(null);
    	}
//    	if (sysUser.getUserName() == null || StringUtils.isBlank(sysUser.getUserName()))
//    	{
//    		return userMapper.selectUserNameByName(sysUser);
//    	}
    	if(sysUser.getUserType()==null || sysUser.getUserType()=="")
    	{
    	internalUser = userMapper.selectUserNameByName(sysUser);
    	internalUser.addAll(userMapper.selectVenNameByName(sysUser));
    	}
    	else if(sysUser.getUserType().equals("00")){
            internalUser = userMapper.selectUserNameByName(sysUser);
        }else if(sysUser.getUserType().equals("01")){
            internalUser =  userMapper.selectVenNameByName(sysUser);
        }
    	return internalUser;
    }

    /**
     * 使用正则表达式来判断字符串中是否包含字母
     * @param str 待检验的字符串
     * @return 返回是否包含
     * true: 包含字母 ;false 不包含字母
     */
    public boolean judgeContainsStr(String str) {
        String regex=".*[a-zA-Z]+.*";
        Matcher m=Pattern.compile(regex).matcher(str);
        return m.matches();
    }

    /**
     * 通过用户名查询用户
     *
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserByLoginName(String userName)
    {
    	SysUser newSysUser = userMapper.selectUserByLoginName(userName);
    	if (newSysUser == null)
    	{
    		SysUser oldSysUser = userMapper.selectUserByLoginNameOld(userName);
    		if (oldSysUser != null && oldSysUser.getLoginName() != null)
    		{
    			return oldSysUser;
    		}
    		else
    		{
    			return newSysUser;
    		}
    	}
    	else
    	{
    		return newSysUser;
    	}

    }

    /**
     * 通过手机号码查询用户
     *
     * @param phoneNumber 手机号码
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserByPhoneNumber(String phoneNumber)
    {
        return userMapper.selectUserByPhoneNumber(phoneNumber);
    }

    /**
     * 通过邮箱查询用户
     *
     * @param email 邮箱
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserByEmail(String email)
    {
        return userMapper.selectUserByEmail(email);
    }

    /**
     * 通过用户ID查询用户
     *
     * @param userId 用户ID
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserById(Long userId)
    {
        return userMapper.selectUserById(userId);
    }

    /**
     * 通过用户ID查询用户(批量)
     *
     * @param userId 用户ID
     * @return 用户对象信息
     */
    @Override
    public List<SysUser> selectUserByIdlist(String userIdlist)
    {
    	if (StringUtils.isNotEmpty(userIdlist) && userIdlist != null && judgeContainsStr(userIdlist))
    	{
    		userIdlist = null;
    	}
        return userMapper.selectUserByIdlist(userIdlist);
    }

    /**
     * 将用户id和供应商id对应关系插入关系表
     * @param userId
     * @param supplierId
     * @return
     */
    @Override
    public int insertSuId(Long userId , Long supplierId)
    {
    	return userMapper.insertSuId(userId,supplierId);
    }

    /**
     * 通过用户ID删除用户
     *
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    public int deleteUserById(Long userId)
    {
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 删除用户与岗位表
        userPostMapper.deleteUserPostByUserId(userId);
        // 删除用户与供应商表
        userSupplierMapper.deleteUserSupplierByUserId(userId);
        // 删除用户与基地表
        userFactoryMapper.deleteUserFactoryByUserId(userId);
        return userMapper.deleteUserById(userId);
    }

    /**
     * 批量删除用户信息
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteUserByIds(String ids) throws BusinessException
    {
        Long[] userIds = Convert.toLongArray(ids);
        for (Long userId : userIds)
        {
            if (SysUser.isAdmin(userId))
            {
                throw new BusinessException("不允许删除超级管理员用户");
            }
        }
        return userMapper.deleteUserByIds(userIds);
    }

    /**
     * 新增保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertUser(SysUser user)
    {
        // 新增用户信息
        int rows = userMapper.insertUser(user);
        // 新增用户岗位关联
        insertUserPost(user);
        // 新增用户与角色管理
        insertUserRole(user);
        // 新增用户与基地管理
        insertUserFactory(user);
        // 新增用户与供应商管理
        insertUserSupplier(user);
        return rows;
    }

    /**
     * 修改保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateUser(SysUser user)
    {
        Long userId = user.getUserId();
        // 删除用户与角色管理
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 新增用户与角色管理
        insertUserRole(user);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPostByUserId(userId);
        // 新增用户与岗位管理
        insertUserPost(user);
        // 删除用户与基地关联
        userFactoryMapper.deleteUserFactoryByUserId(userId);
        // 新增用户与基地管理
        insertUserFactory(user);
        // 删除用户与供应商关联
        userSupplierMapper.deleteUserSupplierByUserId(userId);
        // 新增用户与供应商管理
        insertUserSupplier(user);
        return userMapper.updateUser(user);
    }

    /**
     * 修改用户个人详细信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserInfo(SysUser user)
    {
        return userMapper.updateUser(user);
    }

    /**
     * 通过用户id获取供应商字符串
     * @return
     */
    public String[] selectVendorCodes(String userId)
    {
    	String[] s = userMapper.selectVendorCodes(userId).split(",");
    	return s;
    }

    /**
     * 修改用户密码
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int resetUserPwd(SysUser user)
    {
        return updateUserInfo(user);
    }

    /**
     * 新增用户角色信息
     *
     * @param user 用户对象
     */
    public void insertUserRole(SysUser user)
    {
        List<Long> roles = user.getRoleIds();
        if (StringUtils.isNotNull(roles))
        {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>();
            for (Long roleId : roles)
            {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(user.getUserId());
                ur.setRoleId(roleId);
                list.add(ur);
            }
            if (list.size() > 0)
            {
                userRoleMapper.batchUserRole(list);
            }
        }
    }

    /**
     * 新增用户基地信息
     *
     * @param user 用户对象
     */
    public void insertUserFactory(SysUser user)
    {
        List<Long> factorys = user.getFactoryIds();
        if (StringUtils.isNotNull(factorys))
        {
            // 新增用户与基地管理
            List<SysUserFactory> list = new ArrayList<SysUserFactory>();
            for (Long factoryId : factorys)
            {
            	SysUserFactory uf = new SysUserFactory();
                uf.setUserId(user.getUserId());
                uf.setFactoryId(factoryId);
                list.add(uf);
            }
            if (list.size() > 0)
            {
                userFactoryMapper.batchUserFactory(list);
            }
        }
    }


    /**
     * 新增用户供应商信息
     *
     * @param user 用户对象
     */
    public void insertUserSupplier(SysUser user)
    {
        List<Long> suppliers = user.getSupplierIds();
        if (StringUtils.isNotNull(suppliers))
        {
            // 新增用户与角色管理
            List<SysUserSupplier> list = new ArrayList<SysUserSupplier>();
            for (Long supplierId : suppliers)
            {
                SysUserSupplier us = new SysUserSupplier();
                us.setUserId(user.getUserId());
                us.setSupplierId(supplierId);
                list.add(us);
            }
            if (list.size() > 0)
            {
                userSupplierMapper.batchUserSupplier(list);
            }
        }
    }

    /**
     * 新增用户岗位信息
     *
     * @param user 用户对象
     */
    public void insertUserPost(SysUser user)
    {
        Long[] posts = user.getPostIds();
        if (StringUtils.isNotNull(posts))
        {
            // 新增用户与岗位管理
            List<SysUserPost> list = new ArrayList<SysUserPost>();
            for (Long postId : posts)
            {
                SysUserPost up = new SysUserPost();
                up.setUserId(user.getUserId());
                up.setPostId(postId);
                list.add(up);
            }
            if (list.size() > 0)
            {
                userPostMapper.batchUserPost(list);
            }
        }
    }

    /**
     * 校验用户名称是否唯一
     *
     * @param loginName 用户名
     * @return
     */
    @Override
    public String checkLoginNameUnique(String loginName)
    {
        int count = userMapper.checkLoginNameUnique(loginName);
        if (count > 0)
        {
            return UserConstants.USER_NAME_NOT_UNIQUE;
        }
        return UserConstants.USER_NAME_UNIQUE;
    }

    /**
     * 校验用户名称是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public String checkPhoneUnique(SysUser user)
    {

        int info = userMapper.checkPhoneUnique(user.getPhonenumber());
        if (info > 0)
        {
            return UserConstants.USER_PHONE_NOT_UNIQUE;
        }
        return UserConstants.USER_PHONE_UNIQUE;
    }

    /**
     * 校验email是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public String checkEmailUnique(SysUser user)
    {

        int info = userMapper.checkEmailUnique(user.getEmail());
        if (info > 0)
        {
            return UserConstants.USER_EMAIL_NOT_UNIQUE;
        }
        return UserConstants.USER_EMAIL_UNIQUE;
    }

    /**
     * 查询用户所属角色组
     *
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    public String selectUserRoleGroup(Long userId)
    {
        List<SysRole> list = roleMapper.selectRolesByUserId(userId);
        StringBuffer idsStr = new StringBuffer();
        for (SysRole role : list)
        {
            idsStr.append(role.getRoleName()).append(",");
        }
        if (StringUtils.isNotEmpty(idsStr.toString()))
        {
            return idsStr.substring(0, idsStr.length() - 1);
        }
        return idsStr.toString();
    }

    /**
     * 查询用户所属基地组
     *
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    public String selectUserFactoryGroup(Long userId)
    {
        List<SysFactory> list = factoryMapper.selectFactorysByUserId(userId);
        StringBuffer idsStr = new StringBuffer();
        for (SysFactory role : list)
        {
            idsStr.append(role.getFactoryName()).append(",");
        }
        if (StringUtils.isNotEmpty(idsStr.toString()))
        {
            return idsStr.substring(0, idsStr.length() - 1);
        }
        return idsStr.toString();
    }

    /**
     * 查询用户所属供应商组
     *
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    public String selectUserSupplierGroup(Long userId)
    {
        List<SysSupplier> list = supplierMapper.selectSuppliersByUserId(userId);
        StringBuffer idsStr = new StringBuffer();
        for (SysSupplier role : list)
        {
            idsStr.append(role.getSupplierName()).append(",");
        }
        if (StringUtils.isNotEmpty(idsStr.toString()))
        {
            return idsStr.substring(0, idsStr.length() - 1);
        }
        return idsStr.toString();
    }

    /**
     * 根据用户id查询用户绑定的供应商信息
     * @param userId
     * @return
     */
    public List<SysSupplier> selectSuppliersByUserId(Long userId)
    {
    	return supplierMapper.selectSuppliersByUserId(userId);
    }

    /**
     * 查询用户所属岗位组
     *
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    public String selectUserPostGroup(Long userId)
    {
        List<SysPost> list = postMapper.selectPostsByUserId(userId);
        StringBuffer idsStr = new StringBuffer();
        for (SysPost post : list)
        {
            idsStr.append(post.getPostName()).append(",");
        }
        if (StringUtils.isNotEmpty(idsStr.toString()))
        {
            return idsStr.substring(0, idsStr.length() - 1);
        }
        return idsStr.toString();
    }

    /**
     * 导入用户数据
     *
     * @param userList 用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importUser(List<SysUser> userList, Boolean isUpdateSupport, String operName)
    {
        if (StringUtils.isNull(userList) || userList.size() == 0)
        {
            throw new BusinessException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        String password = configService.selectConfigByKey("sys.user.initPassword");
        for (SysUser user : userList)
        {
            try
            {
                // 验证是否存在这个用户
                SysUser u = userMapper.selectUserByLoginName(user.getLoginName());
                if (StringUtils.isNull(u))
                {
                    user.setPassword(Md5Utils.hash(user.getLoginName() + password));
                    user.setCreateBy(operName);
                    this.insertUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getLoginName() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    user.setUpdateBy(operName);
                    this.updateUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getLoginName() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、账号 " + user.getLoginName() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getLoginName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new BusinessException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 用户状态修改
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int changeStatus(SysUser user)
    {
        if (SysUser.isAdmin(user.getUserId()))
        {
            throw new BusinessException("不允许修改超级管理员用户");
        }
        return userMapper.updateUser(user);
    }

    /* (non-Javadoc)
     * @see com.ruoyi.system.service.ISysUserService#selectUserHasRole(java.lang.Long)
     */
    @Override
    public Set<Long> selectUserIdsHasRoles(Long[] roleIds)
    {
        return ArrayUtil.isNotEmpty(roleIds) ? userMapper.selectUserIdsHasRoles(roleIds) : null;
    }

    /* (non-Javadoc)
     * @see com.ruoyi.system.service.ISysUserService#selectUserInDept(java.lang.Long)
     */
    @Override
    public Set<Long> selectUserIdsInDepts(Long[] deptIds)
    {
        return ArrayUtil.isNotEmpty(deptIds) ? userMapper.selectUserIdsInDepts(deptIds) : null;
    }

    @Override
    public List<SysUser> selectWithoutPasswordUser() {
        return userMapper.selectWithoutPasswordUser();
    }

    @Override
    public String insertOldUser(Long userId)
    {
        String result = "1";
        //将原公司账号移至sys_user_old表中，用来实现供应商代码（新供应商账号）和供应商名称（老供应商账号）均可登录系统
        if (!userMapper.checkOldUser(userId))
        {

            try {
                userMapper.insertUserOldByUserId(userId);
            } catch (Exception e) {
                result = "发放临时供应商编码，userId:" + userId + " ,写入old用户表失败，请联系管理员！";
                log.error(result, e);
                return result;
            }

        }
        return result;
    }

}
